package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.qbdms.model.WQbdFalProblemreset;
import java.io.PrintWriter;

import com.ccp.dev.core.util.TimeUtil;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.enums.FlowStatusEnum;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysRole;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.SysOrgService;
import com.ccp.dev.workflow.model.ProcessRun;
import com.ccp.dev.workflow.model.TaskOpinion;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;
import com.ccp.dev.workflow.service.TaskOpinionService;
import com.google.common.collect.Maps;
import net.sf.json.JSONObject;
import java.nio.charset.StandardCharsets;
import com.ccp.dev.qbdms.model.WQbdDailyInspect;
import com.ccp.dev.qbdms.service.WQbdDailyInspectService;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.core.basic.annotion.Action;
import java.util.Date;
import java.util.List;

import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.ModelMap;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 综合质量管理日常检查 信息操作处理控制器
 * 
 * @author rh
 * @date 2020-09-21 10:36:37
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "综合质量管理日常检查")
@RequestMapping("/qbdms/wQbdDailyInspect")
public class WQbdDailyInspectController extends SysBaseController{
	@Resource
	private WQbdDailyInspectService wQbdDailyInspectService;

    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private ProcessRunService processRunService;
    @Resource
    private TaskOpinionService taskOpinionService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: rh
     * @date: 2020-09-21 10:36:37
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到综合质量管理日常检查首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, ModelMap modelMap) {
        try {
            // 当前登录用户
            String currentUserId = ContextUtil.getCurrentUserId();
            modelMap.put("currentUserId", currentUserId);

            SysRole sysRole = (SysRole) request.getSession().getAttribute(SysRole.CURRENT_SYSROLE);
            if (sysRole.getAlias().equals("bpm_zlzhzly") || sysRole.getAlias().equals("bpm_qnzl")) {
                modelMap.put("canEdit", "true");
            } else {
                modelMap.put("canEdit", "false");
            }
            modelMap.put("rolealis", sysRole.getAlias());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 系统等级
        modelMap.put("currentSystemLevel", BaseUtil.getCurrentSystemLevel());
        return "wQbdDailyInspect/list";
    }

    /**
    * 功能描述: 附带检索条件的分页查询
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: rh
    * @date: 2020-09-21 10:36:37
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询综合质量管理日常检查",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            // 没有排序,默认按照课题评审会会议时间倒序排列,课题评审会会议时间相同的情况下按创建时间倒序排列
            queryFilter.addFilter("orderField", "inspectdate");
            queryFilter.addFilter("orderSeq", "desc");
        }
        // 添加通用查询条件
        ZhiLiangConst.addQueryFilter(queryFilter);

        //本单位的已提交的才能看到
        //分页数据
        List<WQbdDailyInspect> pageDatas = wQbdDailyInspectService.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        //判断流程状态
        ZhiLiangConst.isDataAllowEditByFlowStatus(pageDatas);

        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: rh
     * @date: 2020-09-21 10:36:37
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到综合质量管理日常检查新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);

        SysRole sysRole = (SysRole) request.getSession().getAttribute(SysRole.CURRENT_SYSROLE);
        if (sysRole.getAlias().equals("bpm_qnzl")) {
            modelMap.put("isInclude", "true");
        }
        if (StringUtils.isNotBlank(id)) {
            WQbdDailyInspect wQbdDailyInspect = wQbdDailyInspectService.getOneById(id);
            modelMap.put("flowStatus", wQbdDailyInspect.getFlowStatus());
        }
        List<SysOrg> resultOrg = Lists.newArrayList();
        List<SysOrg> listOrg = sysOrgService.querySubSysOrgBySupOrgIdNoChild(sysOrgService.getSysOrgByOrgCode("1734").getOrgId());
        for (SysOrg org : listOrg) {
            if (org.getCode().equals("wrj")) {
                List<SysOrg> listOrgSub =sysOrgService
                        .querySubSysOrgBySupOrgIdNoChild(sysOrgService.getSysOrgByOrgCode("wrj").getOrgId());
                resultOrg.addAll(listOrgSub);
            } else {
                resultOrg.add(org);
            }
        }
        modelMap.put("researchRoomList", JSON.toJSONString(resultOrg));
        if (StringUtil.isEmpty(id)) {
            SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
            SysOrg sysOrg = (SysOrg) ContextUtil.getCurrentOrg();
            modelMap.put("filldept", sysOrg.getOrgName());
            modelMap.put("fillman", sysUser.getFullName());
            modelMap.put("filldate", TimeUtil.getCurrentDate());
            modelMap.put("fillmanaccount", sysUser.getAccount());
            modelMap.put("filldeptid", sysOrg.getCode());
        }
        return "wQbdDailyInspect/add";
    }

    /**
    * 功能描述:  数据保存通用方法
    *
    * @param: wQbdDailyInspect 保存的对象
    * @return: java.lang.Object
    * @auther: rh
    * @date: 2020-09-21 10:36:37
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存综合质量管理日常检查数据",detail="<#if isAdd>新增<#else>编辑</#if>综合质量管理日常检查数据<#if success>成功<#else>失败</#if>")
    public Object save(@RequestBody WQbdDailyInspect wQbdDailyInspect, HttpServletRequest request) {
        String id = wQbdDailyInspect.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            //新增数据前生成随机Id
            wQbdDailyInspect.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdDailyInspect);

            wQbdDailyInspect.setTenantId(ContextUtil.getCurrentUserTenantId());
            wQbdDailyInspect.setCreateBy(ContextUtil.getCurrentUserId());
            wQbdDailyInspect.setCreateTime(new Date());
            wQbdDailyInspect.setFlowStatus(FlowStatusEnum.NOT_SUBMIT.getValue());
            result = wQbdDailyInspectService.add(wQbdDailyInspect);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdDailyInspect);

            wQbdDailyInspect.setUpdateBy(ContextUtil.getCurrentUserId());
            wQbdDailyInspect.setUpdateTime(new Date());

            //修改操作
            result = wQbdDailyInspectService.update(wQbdDailyInspect);
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        Map<String,Object> idMap= Maps.newHashMap();
        idMap.put("id",wQbdDailyInspect.getId());
        return result > 0 ? getResultDataSuccess("save.success",idMap) : getResultDataError("save.failure");
    }

    /**
    * 功能描述: 跳转到详情页面
    *
    * @return: java.lang.String
    * @auther: rh
    * @date: 2020-09-21 10:36:37
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到综合质量管理日常检查详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String flag = RequestUtil.getString(request, "flag");
        modelMap.put("flag", flag);
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        WQbdDailyInspect wQbdDailyInspect = wQbdDailyInspectService.getOneById(id);
        modelMap.put("flowStatus", wQbdDailyInspect.getFlowStatus());
        String runId="";
        List<TaskOpinion> taskOpinionNewList = new ArrayList<TaskOpinion>();
        ProcessRun processRun=processRunService.getByBusinessKey(id);
        if(BeanUtils.isNotEmpty(processRun)){
            runId=processRun.getRunId();
            List<TaskOpinion> taskOpinionList = taskOpinionService.getByRunId(runId);
            for(TaskOpinion taskOpinion:taskOpinionList){
                if(taskOpinion.getEndTime()!=null){
                    taskOpinionNewList.add(taskOpinion);
                }
            }
        }
        modelMap.put("taskOpinionNewList", taskOpinionNewList);
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        String hideCancelBtn = RequestUtil.getString(request, "hideCancelBtn");
        modelMap.put("hideCancelBtn", hideCancelBtn);
        modelMap.put("runId", runId);
        return "wQbdDailyInspect/particulars";
    }

    /**
    * 功能描述: 根据主键id获取一条数据的通用查询方法
    *
    * @param: id 参数对象必须是"id"
    * @return: java.lang.Object
    * @auther: rh
    * @date: 2020-09-21 10:36:37
    */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询综合质量管理日常检查的一条数据",detail="根据主键id查询综合质量管理日常检查的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id, ModelMap modelMap) {
        WQbdDailyInspect wQbdDailyInspect = wQbdDailyInspectService.getOneById(id);
        if (null == wQbdDailyInspect) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        FlowStatusEnum flowStatusEnum = FlowStatusEnum.getEnumByValue(wQbdDailyInspect.getFlowStatus());
        wQbdDailyInspect.setFlowStatusStr(flowStatusEnum.getName());
        modelMap.addAttribute("data", wQbdDailyInspect);
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdDailyInspect);
    }

    /**
    * 功能描述: 根据主键ID删除数据的通用删除方法
    *
    * @param: id 参数名称必须是"id"
    * @return: java.lang.Object
    * @auther: rh
    * @date: 2020-09-21 10:36:37
    */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除综合质量管理日常检查数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) throws Exception{
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdDailyInspect wQbdDailyInspect = wQbdDailyInspectService.getOneById(key);

            //判断流程状态
            FlowStatusEnum flowStatusEnum = FlowStatusEnum.getEnumByValue(wQbdDailyInspect.getFlowStatus());
            if (!flowStatusEnum.isDel()) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，不允许删除流程未结束数据！");
            }
            if (!userId.equals(wQbdDailyInspect.getCreateBy())) {
                return fail("删除失败！只能删除自己创建的数据！");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("delete.failure.message");
        }
        //流程实例删除
        for (String key : ids) {
            WQbdDailyInspect wQbdDailyInspect  = wQbdDailyInspectService.getOneById(key);
            if(!wQbdDailyInspect.getFlowStatus().equals(FlowStatusEnum.NOT_SUBMIT.getValue()) && StringUtil.isNotEmpty(wQbdDailyInspect.getFlowStatus())){
                ProcessRun processRun = processRunService.getByBusinessKey(key);
                if(processRun!=null){
                    processRunService.deleteByProcessRun(processRun);
                }
            }
        }
        int result = wQbdDailyInspectService.delByIdArray(id.split(","));
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
    * 功能描述: 跳转到导入页面
    *
    * @return: java.lang.String
    * @auther: hw
    * @date: 2019-12-25 19:21:40
    */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到综合质量管理日常检查导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdDailyInspect/import";
    }

    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到综合质量管理日常检查选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdDailyInspect.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }

    /**
    * 功能描述: 导出综合质量管理日常检查数据信息
    *
    * @param: [request] http请求
    * @return: java.lang.Object
    * @auther: rh
    * @date: 2020-09-21 10:36:37
    */
    @RequestMapping("/exportData")
    @Action(description="导出综合质量管理日常检查数据信息",detail="导出综合质量管理日常检查数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);

        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        List<WQbdDailyInspect> wQbdDailyInspects = this.wQbdDailyInspectService.queryAll(queryFilter);
        if (wQbdDailyInspects.isEmpty()) {
            wQbdDailyInspects.add(new WQbdDailyInspect());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, wQbdDailyInspects, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
    * 导入资源文件
    * @param request
    * @param response
    * @throws Exception
    */
    @RequestMapping("/importData")
    public void importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        MultipartFile multipartFile = request.getFile("file");
        PrintWriter writer = response.getWriter();
        try {
            String fileName = multipartFile.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            //读取excel文件，并获取每行的数据
            ExcelReader excelReader = new ExcelReader();
            TableEntity excelEntity = excelReader.readFile(multipartFile.getInputStream());
            List<DataEntity> rowDataEntityList = excelEntity.getDataEntityList();

            List<WQbdDailyInspect> listToInsert = new ArrayList<>();
            for (DataEntity dataEntity : rowDataEntityList) {
                //获取每列的数据
                List<FieldEntity> fieldEntityList = dataEntity.getFieldEntityList();
                WQbdDailyInspect dataToInsert = new WQbdDailyInspect();
                int i =0;
                //根据列的顺序，给相应的对象赋值
                for (FieldEntity fieldEntity : fieldEntityList) {
                    //if(i==0){
                        //dataToInsert.setName(fieldEntity.getValue());
                    //}
                    i++;
                }
                dataToInsert.setId(UUIDUtils.getUUIDFor32());
                listToInsert.add(dataToInsert);
            }
            wQbdDailyInspectService.addList(listToInsert);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            JSONObject json = JSONObject.fromObject(getResultDataSuccess("operation.success"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            JSONObject json = JSONObject.fromObject(getResultDataError("operation.failure"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
        }
    }

    /**
     * 功能描述: 启动流程
     */
    @PostMapping("/run")
    @ResponseBody
    @Action(description="启动综合质量管理日常检查流程",detail="启动流程<#if success>成功<#else></#if>")
    public Object run(HttpServletRequest request,@RequestBody WQbdDailyInspect wQbdDailyInspect){
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        //实体主键
        String id = wQbdDailyInspect.getId();
        int isList = RequestUtil.getInt(request,"isList",1);
        ProcessCmd  processCmd = new ProcessCmd();
        //流程Key
        processCmd.setModelKey("rcjcsplc");
        processCmd.setUserAccount(sysUser.getAccount());
        try {
            if(isList == 1){
                wQbdDailyInspect = wQbdDailyInspectService.getOneById(id);
            }
            processCmd.setBusinessKey(id);
            processRunService.startProcess(processCmd);
            wQbdDailyInspect.setFlowStatus(FlowStatusEnum.APPROVAL_ING2.getValue());
            wQbdDailyInspectService.update(wQbdDailyInspect);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("flow.start.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("flow.start.failure");
        }
    }


}
